package com.zb.service.Impl;

import com.alibaba.fastjson.JSON;
import com.zb.client.SkuFeignClient;
import com.zb.dto.SkuDTO;
import com.zb.dto.SpuDTO;
import com.zb.entity.TbOrderItemModel;
import com.zb.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFeignClient skuFeignClient;
    @Override
    public Boolean addItem(String uname, String skuId, Integer num) {
        if (num<=0){
            redisTemplate.boundHashOps("cart:"+uname).delete(num);
        }
        Map<String, Object> skuItemDTO = skuFeignClient.item(skuId);
        Map<String, Object> skuMap = (Map<String, Object>) skuItemDTO.get("skuDTO");
        Map<String, Object> spuMap = (Map<String, Object>) skuItemDTO.get("spuDTO");

        SkuDTO skuDTO = JSON.parseObject(JSON.toJSONString(skuMap), SkuDTO.class);
        SpuDTO spuDTO = JSON.parseObject(JSON.toJSONString(spuMap), SpuDTO.class);

        TbOrderItemModel tbOrderItemModel=new TbOrderItemModel();
        tbOrderItemModel.setCategoryId1(spuDTO.getCategory1Id());
        tbOrderItemModel.setCategoryId2(spuDTO.getCategory2Id());
        tbOrderItemModel.setCategoryId3(spuDTO.getCategory3Id());
        tbOrderItemModel.setSpuId(spuDTO.getId());
        tbOrderItemModel.setSkuId(skuDTO.getId());
        tbOrderItemModel.setName(skuDTO.getName());
        tbOrderItemModel.setPrice(skuDTO.getPrice());
        tbOrderItemModel.setNum(num);
        tbOrderItemModel.setMoney(skuDTO.getPrice()*num);
        tbOrderItemModel.setImage(skuDTO.getImage());
        tbOrderItemModel.setWeight(skuDTO.getWeight());
        redisTemplate.boundHashOps("cart:"+uname).put(skuId,tbOrderItemModel);


        return true;
    }

    @Override
    public List<TbOrderItemModel> list(String uname) {

        return redisTemplate.boundHashOps("cart:"+uname).values();
    }

    @Override
    public Boolean remove(String username, String skuId) {

      return   redisTemplate.boundHashOps("cart:"+username).delete(skuId)>0?true:false;
    }

    @Override
    public List<TbOrderItemModel> select(String[] skuIds, String username) {
        List<TbOrderItemModel> list =new ArrayList<>();
        for (String skuId : skuIds) {
            list.add((TbOrderItemModel) redisTemplate.boundHashOps("cart:"+username).get(skuId));
        }
        return list;






    }
}
